import urllib2
import urllib
from django.utils import simplejson as json
import time,datetime
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import mail

#capacities = ['16gb', '32gb', '64gb']
#itemTypes = ['IPAD2012_WIFI', 'IPHONE4S']
itemTypes = ['IPAD2012_WIFI']
capacities = ['16gb']
colors = ['black']


def check(handler, itemType, color, capacity): 
    url = 'http://store.apple.com/hk-zh/variationUpdate/' + itemType + '?option.dimensionColor=' + color +'&option.dimensionCapacity=' + capacity;
    if 'IPHONE' in itemType:
        url += '&carrierPolicyType=UNLOCKED';
    response = json.loads(urllib2.build_opener().open(url).read());
#    response = json.loads('{"body":{"content":{"selected":{"purchaseOptions":{"isBuyable":true}}}}}')
    #handler.response.out.write(response)
    isBuyable = response['body']['content']['selected']['purchaseOptions']['isBuyable']
    return isBuyable;

class MainHandler(webapp.RequestHandler):
    def get(self):
        for itemType in itemTypes:
            for color in colors:
                for capacity in capacities:
                    isBuyable = check(self, itemType, color, capacity)
                    name = itemType + ' ' + color + ' ' + capacity;
                    self.response.out.write(name + ' buyable is ' + str(isBuyable) + '<br>')
                    if isBuyable:
                        subject = name + " is buyable";
                        #mail.send_mail(sender="huxiaoping1127@gmail.com", to="huxiaoping1127@gmail.com", subject= subject, body="as Title");
                        self.response.out.write('mail sent' + '<br>')



def main():
    application = webapp.WSGIApplication([('/iphone/scanner', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
